package com.yupi.xupicturebackend.controller;

import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.utils.IOUtils;
import com.thoughtworks.xstream.core.BaseException;
import com.yupi.xupicturebackend.annotation.AuthCheck;
import com.yupi.xupicturebackend.common.BaseResponse;
import com.yupi.xupicturebackend.common.ResultUtils;
import com.yupi.xupicturebackend.constant.UserConstant;
import com.yupi.xupicturebackend.exception.BusinessException;
import com.yupi.xupicturebackend.exception.ErrorCode;
import com.yupi.xupicturebackend.manager.CosManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

/**
 * @author 21829
 */
@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {


    @Resource
    private CosManager cosManager;


    /**
     * 测试文件上传功能
     * @param multipartFile 文件
     * @return 地址
     */
    @PostMapping("/test/upload")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<String> testUploadFile(@RequestPart("file") MultipartFile multipartFile) {
        String filename = multipartFile.getOriginalFilename();
        String filePath = String.format( "/test/%s",filename);
        File file = null;
        try {
            file =  File.createTempFile(filePath,null);
            multipartFile.transferTo(file);
            cosManager.putObject(filePath,file);
            //返回可访问的地址
            return ResultUtils.success(filePath);
        } catch (Exception e) {
            log.error("file upload error,filePath = " + filePath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"上传失败");
        }finally {
            if(file != null){
                //删除临时文件
                boolean delete = file.delete();
                if (!delete){
                    log.error("file delete error,filePath = " + filePath);
                }
            }
        }
    }

    /**
     * 测试文件下载
     * @param filePath 文件路径
     * @param response 响应对象
     */
    @GetMapping("/test/download")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public void testDownloadFile(String filePath, HttpServletResponse response) throws IOException {
        COSObjectInputStream cosObjectInput = null;
        COSObject cosObject = cosManager.getObject(filePath);
        cosObjectInput = cosObject.getObjectContent();
        // 处理下载的流
        try {
            byte[] bytes = IOUtils.toByteArray(cosObjectInput);
            // 设置响应头
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + filePath);
            //写入响应
            response.getOutputStream().write(bytes);
            //刷新
            response.getOutputStream().flush();
        } catch (Exception e) {
            log.error("download file error,filePath = " + filePath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"下载失败");
        }finally {
            if(cosObjectInput != null){
                cosObjectInput.close();
            }
        }
    }


}
